package com.java.teachercode;

public class BreadContainer {
    private static final int CAPCITY = 300;
    private static final int INIT_COUNT = 50;
    private int breadCount;

    public BreadContainer() {
        this(INIT_COUNT);
    }

    public BreadContainer(int breadCount) {
        this.breadCount = breadCount;
    }

    /**
     * 生产面包
     */
    public synchronized void produce(int count, String name) {
        System.out.println(" + " + name + "准备生产面包：" + count + "个.");
        while (this.breadCount + count > CAPCITY) {
            System.out.println(" + " + name + "准备生产面包：" + count + "个，现有" + this.breadCount + "超出容量。");
            try {
                this.wait();
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        // 生产
        this.breadCount += count;
        // 唤醒消费
        System.out.println(" + " + name + "生产面包" + count + "个，现有" + this.breadCount + "，生产结束。");
//		随机唤醒一个
//		this.notify();
        //唤醒所有
        this.notifyAll();

    }

    /**
     * 消费面包
     */
    public synchronized void consume(int count, String name) {
        System.out.println(" - " + name + "准备消费面包：" + count + "个.");
        while (this.breadCount < count) {
            System.out.println(" - " + name + "要消费面包" + count + "个，现有" + this.breadCount + ",不足消费。");
            try {
                this.wait();
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        // 消费
        this.breadCount -= count;
        // 唤醒生产
        System.out.println(" - " + name + "消费面包" + count + "个，现有" + this.breadCount + "，消费结束。");
        this.notifyAll();
    }

    @Override
    public String toString() {
        return "剩余：" + this.breadCount;
    }

}
